package com.greens1995.testmap;

import android.content.Context;
import android.location.Location;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.greens1995.testmap.geohash.GeoHash;
import com.greens1995.testmap.geohash.Test;
import com.greens1995.testmap.model.Person;

import java.util.List;

class ViewpagerAdapter extends PagerAdapter {
    private final List<Person> persons;
    private Context context;
    private Location mainLocation;

    public ViewpagerAdapter(Context context, List<Person> persons) {
        this.persons = persons;
        this.context = context;
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        final Person person = persons.get(position);
        View view = LayoutInflater.from(context).inflate(R.layout.viewpager_layout, null);
        ImageView ivPortrait = (ImageView) view.findViewById(R.id.iv);
        ImageView ivSex = (ImageView) view.findViewById(R.id.iv_sex);
        TextView tvName = (TextView) view.findViewById(R.id.tv_name);
        TextView tvDistance = (TextView) view.findViewById(R.id.tv_distance);
        tvName.setText(person.getTitle());
        if (mainLocation == null) {
            tvDistance.setText("?km");
        } else {
            double dis = Test.GetDistance(mainLocation.getLongitude(), mainLocation.getLatitude(), persons.get(position).getPosition().longitude, persons.get(position).getPosition().latitude);
            tvDistance.setText(dis/1000 + "km");
        }

        ivPortrait.setImageResource(person.getProfilePhoto());
        ivPortrait.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(context, "GeoHash是 " + GeoHash.withBitPrecision(person.getPosition().latitude, person.getPosition().longitude, 30).toBase32(), Toast.LENGTH_SHORT).show();
            }
        });
        container.addView(view);
        return view;
    }

    @Override
    public int getCount() {
        return persons.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        View view = (View) object;
        container.removeView(view);
    }

    public void setMainLocation(Location location) {
        this.mainLocation = location;
    }
}